package dongtaidaili;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @author: 叶子
 * @date: 2022/02/22 10:31
 * 动态代理示例
 **/
//1.编写需要被代理的类和接口
interface DemoInterface {
    String hello(String msg);
}

class DemoImpl implements DemoInterface {
    @Override
    public String hello(String msg) {
        System.out.println("msg=" + msg);
        return "hello";
    }
}

//2.编写代理类，需要实现InvocationHandler接口，重写invoke()方法
class DemoProxy implements InvocationHandler {
    private DemoInterface service;

    public DemoProxy(DemoInterface service) {
        this.service = service;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用方法前...");
        Object returnValue = method.invoke(service, args);
        System.out.println("调用方法后");
        return returnValue;
    }
}

//3.使用 Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
//动态创建代理类对象，通过代理类对象调用业务方方法
public class Solution {
    public static void main(String[] args) {
        DemoProxy proxy = new DemoProxy(new DemoImpl());
        DemoInterface service = (DemoInterface) Proxy.newProxyInstance(DemoInterface.class.getClassLoader(), new Class<?>[]{DemoInterface.class}, proxy);
        System.out.println(service.hello("哈哈哈"));
    }
}